import java.io.*;
import java.util.*;
public class ReplaceString {
    private File f;
    private String old_str;
    private String new_str;
    
    public void setAttributes(String file_path, String old_str, String new_str) {
	this.f = new File(file_path);
	this.old_str = old_str;
	this.new_str = new_str;
    }

    public void setAttributes(File f, String old_str, String new_str) {
	this.f = f;
	this.old_str = old_str;
	this.new_str = new_str;
    }
    
    public String replace() {
	try {
	    if(!f.isFile()) {
		return "File:"+ f.getPath()+ " not found.";
	    }
	    
	    boolean changed = false;
	    StringBuffer sbf = new StringBuffer();
	    BufferedReader  bf_reader = new BufferedReader(new FileReader(f));
	    String in_line = bf_reader.readLine();
	    while(null != in_line) {
		if(in_line != null) {
		    if(in_line.indexOf(old_str) != -1) {
			changed = true;
			sbf.append(in_line.replaceAll(old_str, new_str)+"\n");
		    }
		    else {
			sbf.append(in_line+"\n");
		    }
		}
		in_line =bf_reader.readLine();
	    }
	    
	    bf_reader.close();
	    if(changed) {
		if(f.renameTo(new File(f.getPath()+"."+System.currentTimeMillis()+".changed"))) {
		}
		else {
		    changed = false;
		    return "Error: Can't rename file:"+f.getPath();
		}
	    }
	    
	    if(changed) {
		try {
		    FileWriter fw = new FileWriter(f.getPath());
		    BufferedWriter bfw =  new BufferedWriter ( fw );
		    bfw.write(sbf.toString());
		    bfw.flush();
		    bfw.close();
		    
		    return f.getPath()+" has been changed.";
		}
		catch( IOException e ) {
		    return "Error [400]";
		}
	    }
	    return "No change for file "+f.getPath();
	}
	catch (IOException e) {
	    return "Error [401]";
	}
	catch (Exception e) {
	    return "Error [402]";
	}
    }
}



